package cn.monkey.family.server.domain.shop.item;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.shop.item.ItemDto;
import cn.monkey.family.data.shop.item.ItemQueryRequest;
import cn.monkey.family.data.shop.item.ItemVo;
import com.google.common.base.Strings;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("shop/item")
public class ItemController {

    private final IItemService itemService;


    public ItemController(IItemService itemService) {
        this.itemService = itemService;
    }

    @GetMapping({"{id}", ""})
    Result<?> get(@Context RequestContext requestContext,
                  @PathVariable(value = "id", required = false) String id,
                  @RequestParam(value = "action", required = false) String action,
                  final ItemQueryRequest queryRequest,
                  @PageableDefault Pageable pageable) {
        if (!Strings.isNullOrEmpty(id)) {
            return this.itemService.readById(requestContext, id);
        }
        if ("readAll".equals(action)) {
            return this.itemService.readAll(requestContext, queryRequest, pageable.getSort());
        }
        if ("getBanner".equals(action)) {
            return this.itemService.readBanner(requestContext, queryRequest, pageable);
        }
        return this.itemService.readPage(requestContext, queryRequest, pageable);
    }


    @PostMapping
    Result<ItemVo> add(@Context RequestContext requestContext,
                       @RequestBody ItemDto item) {
        return this.itemService.create(requestContext, item);
    }


    @PutMapping("{id}")
    Result<ItemVo> update(@Context RequestContext requestContext,
                          @PathVariable("id") String id,
                          @RequestBody ItemDto itemDto) {
        return this.itemService.update(requestContext, id, itemDto);
    }

    @DeleteMapping("{id}")
    Result<Void> delete(@Context RequestContext requestContext,
                        @PathVariable("id") String id) {
        return this.itemService.delete(requestContext, id);
    }
}
